package sdfi.lee.SetFileToDB;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.jms.Connection;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;

import sdfi.lee.DAO.DAO;
import sdfi.lee.Format.DateFormat;
import sdfi.lee.JMS.ConnectionFactory;
import sdfi.lee.Logger.MyLogger;
import sdfi.lee.Properties.ReaderProperties;
import sdfi.lee.ReaderFromDisk.ReaderNotice;

public class DealwithProfile {
	public static List<String> list=new ArrayList<String>();
	public static List<String> listsgml=new ArrayList<String>();
	public static void main(String[] arg)
	{
		
		
		Session session=null;
		MessageConsumer consumer=null;
		Connection con=ConnectionFactory.getCon();
		String queue="mysql";
		try
		{
		con.start();
		session=con.createSession(false, Session.AUTO_ACKNOWLEDGE);
		consumer=session.createConsumer(session.createQueue(queue));
		consumer.setMessageListener(new MessageListener(){
			public void onMessage(Message message)
			{
				
					MapMessage mapmsg=(MapMessage)message;
					String value="";
					try
					{
						Object obj=mapmsg.getMapNames().nextElement();
						value=mapmsg.getString(obj.toString());
					}
					catch(Exception ee)
					{
						ee.printStackTrace();
					}
					if(!"".equals(value)&&null!=value)
					{
						if(value.startsWith("file"))//处理SGML
						{
							String sign=value.substring(4,5);
							String path=value.substring(value.indexOf(sign)+1);
							String type="others";
							if(value.contains("patents"))
								type="patents";
							else if(value.contains("policy"))
								type="policy";
							else if(value.contains("journals"))
								type="journals";
							else if(value.contains("notice"))
								type="notice";
							String operate="delete";
							if("+".equals(sign))
								operate="add";
							if(path==null||"".equals(path)) return ;
							DealwithProfile.setToSMGLDB(path, type, operate);
							
						}
						else//处理profile
						{
							String regex="\\s+";
							String s[]=value.split(regex);
							if(s.length>0)
							{
								DealwithProfile.setProfileToDB(s[1], s[0]);
							}
							
						}
					}
					
				
			}
		});
		}
		catch(Exception ee)
		{
			ee.printStackTrace();
		}
		}
	/*合并完成的profile*/
	public synchronized static boolean setProfileToDB(String pathnew,String type)
{
		StringBuffer sb=new StringBuffer();
		String disc="";
		try
		{
			disc=new ReaderProperties().getProperty("merge");
		}
		catch(Exception ee)
		{
			disc="v:";
			ee.printStackTrace();
		}
		pathnew=disc+pathnew;
		
		try
		{
			
			File f=new File(pathnew);
			MyLogger.Logger("profile operation "+type+" file:"+pathnew+"file exitst?"+f.exists(),null,"info");
			if(!f.exists())
				{
					return false;
				}
			InputStream is=new FileInputStream(f);
			InputStreamReader isr=new InputStreamReader(is,"utf-8");
			BufferedReader reader=new BufferedReader(isr);
			sb=new StringBuffer("");
			String line=reader.readLine();
			while(line!=null)
			{
				sb.append(line);
				line=reader.readLine();
			}
			reader.close();
			isr.close();
			is.close();
			String stype="0";
			if(pathnew.contains("product")) stype="-1";
			else if(pathnew.contains("achievement")) stype="0";
			else if(pathnew.contains("yiqi")) stype="1";
			else if(pathnew.contains("medicaldevice")) stype="2";
			else if(pathnew.contains("medicament")) stype="3";
			else if(pathnew.contains("orgnization")) stype="4";
			else if(pathnew.contains("disease")) stype="5";
			else if(pathnew.contains("patent")) stype="7";
			else if(pathnew.contains("paper")) stype="8";
			else if(pathnew.contains("even")) stype="9";
			else if(pathnew.contains("location")) stype="10";
			else if(pathnew.contains("time")) stype="11";
			else if(pathnew.contains("periodical")) stype="12";
	
			String sql="update answer set type='"+stype+"',answer='"+sb.toString()+"',andate='"+DateFormat.getDateFormat(new Date(), "yyyy-MM-dd HH:mm:ss")+"'"+" " +
					"where path='"+pathnew+"'";
			if("add".equals(type))
			{
				sql="insert into answer(type,answer,andate,path)value('"+stype+"','"
					+sb.toString()+"','"+DateFormat.getDateFormat(new Date(), "yyyy-MM-dd HH:mm:ss")+"','"+pathnew+"')";
				
			}
		
			list.add(sql);
			if(list.size()>=50)
			{
				DealwithProfile.setToDB(list);
			}
			
			
			
		}
		catch(Exception ee)
		{
			ee.printStackTrace();
			return false;
		}
		return true;
	}

	/*处理SMGL文件*/
	public synchronized static void setToSMGLDB(String path,String type,String operate)
	{
		
		String disc="z:";
		try
		{
			disc=new ReaderProperties().getProperty("search");
			
		}
		catch(Exception ee)
		{
			disc="z:";
			ee.printStackTrace();
		}
		path=disc+path;
		MyLogger.Logger("msg operation "+operate+" file:"+path,null,"info");
		String  sql="";
		if(!"add".equals(operate))
			sql="delete from rollnotice where rollpath='"+path+"'";
		else
		{
			ReaderNotice reader=new ReaderNotice(path);
			String title="";
			String date=DateFormat.getDateFormat(new Date(), "yyyy-MM-dd");
			sql="insert into rollnotice(rolltype,rollpath,rolltitle,rolldate)values('";
			try
			{
				if("notice".equals(type))//1
				{	   /*
						<title></title>
						<crawltime></crawltime>
						<source></source>
						<body></body>

				 		*/
					title=reader.getNodeByName("title");
					if(title==null) return ;
					date=reader.getNodeByName("modifytime");
					sql+=1;
				}else
					if("policy".equals(type))//2
					{	
						/*
						 * <title>
						 * <crawltime>
						 * <modifytime>
						 * <source>
						 * <body>
						 * */
			
						title=reader.getNodeByName("title");
						if(title==null) return ;
						date=reader.getNodeByName("modifytime");
						sql+=2;
					}else
						if("journals".equals(type))//期刊杂志3
						{
							/*
							 * <source>
							 * <journal>
							 * <title>
							 * <period>
							 * <keyword>
							 * <anthor>
							 * <organization>
							 * <abstracts>
							 * <process_time>
							 * 
							 */
							title=reader.getNodeByName("title");
							if(title==null) return;
							date=reader.getNodeByName("process_time");
							sql+=8;
						}else
							if("patent".equals(type))//成果专利4
							{
								/*
								 * patents
								 * <sourceUrl>
								 * <applyNum>
								 * <applyDate>
								 * <name>
								 * <categoryNum>
								 * <applyPerson>
								 * <designer>
								 * <abstracts>
								 * */
								title=reader.getNodeByName("name");
								if(title==null) return;
								date=reader.getNodeByName("publicDate");
								sql+=6;
							}
							else if("achievement".equals(type))
								{
								/*
								 * achievement
								 * <title>
								 * <source>
								 * <crawltime>
								 * <body>
								 * */
								title=reader.getNodeByName("title");
								if(title==null) return;
								date=reader.getNodeByName("modifytime");
								sql+=7;
								}
							else if("inner".equals(type))
							{
								title=reader.getNodeByName("title");
								if(title==null)return ;
								date=reader.getNodeByName("modifytime");
								sql+=4;
								
							}else if("outer".equals(type))
							{
								title=reader.getNodeByName("title");
								if(title==null)return ;
								date=reader.getNodeByName("modifytime");
								sql+=3;
							}
		
		
			sql+="','"+path+"','"+title+"','"+date+"')";
			listsgml.add(sql);
			if(listsgml.size()>=50)
			{
				DealwithProfile.setToDB(listsgml);
			}
		
		}
		catch(Exception ee)
		{
			MyLogger.Logger(ee.getMessage(), null, "error");
			ee.printStackTrace();
		}
	}
		
		
	}
	
	public synchronized static void setToDB(List<String> list)
	{	
		
			MyLogger.Logger("update db begin.....", null, "info");
			java.sql.Connection con=DAO.openSession().connection();
		
			try
			{
				con.setAutoCommit(false);
			Statement stm=con.createStatement();
			for(String sql:list)
			{
				stm.addBatch(sql);
			}
			MyLogger.Logger("update db end size "+stm.executeBatch().length, null, "info");
			con.commit();
			//con.close();
			}
			catch(Exception ee)
			{
				MyLogger.Logger("Exception when update db "+ee.getMessage(), null, "error");
				ee.printStackTrace();
				try {
					con.rollback();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			finally
			{
				DAO.closeSession();
				list.clear();
			}
		
		
	}
}
